package com.muapet.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.muapet.model.Account;
import com.muapet.model.Order;
import com.muapet.model.Pet;
import com.muapet.model.User;
import com.muapet.model.Variety;
import com.muapet.model.other.Pagination;
import com.muapet.model.other.PetCondition;
import com.muapet.service.IOrderService;
import com.muapet.service.IPetService;
import com.muapet.service.IUserService;
import com.muapet.util.Md5Utils;

@Controller
@RequestMapping("/manage")
public class ManageController {
	private IUserService userService;
	private IPetService petService;
	private IOrderService orderService;

	@Autowired
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@Autowired
	public void setPetService(IPetService petService) {
		this.petService = petService;
	}

	@Autowired
	public void setOrderService(IOrderService orderService) {
		this.orderService = orderService;
	}

	@RequestMapping("/userMgnt")
	public ModelAndView userMgnt() {
		ModelAndView mav = new ModelAndView("mgnt/userMgnt");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/findAllUser")
	@ResponseBody
	public String findAllUser(Pagination pagination) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rows", userService.findAll(pagination));
		resultMap.put("total", userService.countAll());
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/findUserByLoginname")
	@ResponseBody
	public String findUserByLoginname(String loginname, Pagination pagination) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rows",
				userService.findByLoginname(loginname, pagination));
		resultMap.put("total", userService.countByLoginname(loginname));
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/findWaitingUser")
	@ResponseBody
	public String findWaitingUser(Pagination pagination) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rows", userService.findWaitingUser(pagination));
		resultMap.put("total", userService.countWaitingUser());
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/deleteUser")
	@ResponseBody
	public String deleteUser(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (userService.findById(id) == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该用户不存在，请刷新重试！");
		} else {
			Account account = userService.findAccountByUserId(id);
			if (account != null && account.getBalance() > 0.001) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "该用户账户仍有余额，不能删除！");
			} else if (petService.listPetBySeller(id, 1) != null
					&& petService.listPetBySeller(id, 1).size() > 0) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "该用户仍有在售宠物，不能删除！");
			} else if (orderService.listUndoOrdersByUserId(id) != null
					&& orderService.listUndoOrdersByUserId(id).size() > 0) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "该用户仍有交易中订单，不能删除！");
			} else {
				userService.delete(id);
				resultMap.put("msg", "success");
			}
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/passUser")
	@ResponseBody
	public String passUser(Integer id, Boolean pass) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User user = userService.findById(id);
		if (user == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该用户不存在，请刷新重试！");
		} else if (user.getIspass() == null
				|| user.getIspass() != User.USER_ISPASS_WAITING) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该用户不是实名状态待审核用户，请刷新重试！");
		} else {
			if (pass) {
				user.setIspass(User.USER_ISPASS_YES);
			} else {
				user.setIspass(User.USER_ISPASS_NO);
			}
			userService.update(user);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/initUserPwd")
	@ResponseBody
	public String initUserPwd(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User user = userService.findById(id);
		if (user == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该用户不存在，请刷新重试！");
		} else {
			user.setPassword(Md5Utils.md5(user.getLoginname() + "123"));
			userService.update(user);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/initUserPayPwd")
	@ResponseBody
	public String initUserPayPwd(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User user = userService.findById(id);
		Account account = userService.findAccountByUserId(id);
		if (user == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该用户不存在，请刷新重试！");
		} else if (account == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该用户账户不存在！");
		} else {
			userService.updateAccountPwdByUserId(id, user.getPassword());
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/updateAccount")
	public ModelAndView updateAccount(Integer id) {
		ModelAndView mav;
		User user = userService.findById(id);
		Account account = userService.findAccountByUserId(id);
		if (user == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "该用户不存在，请刷新重试！");
		} else if (account == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "该用户账户不存在！");
		} else {
			mav = new ModelAndView("mgnt/updateAccount");
			mav.addObject("user", user);
			mav.addObject("account", account);
		}
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/updateUserAccount")
	@ResponseBody
	public String updateUserAccount(Integer userId, Double money, Boolean isAdd) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User user = userService.findById(userId);
		Account account = userService.findAccountByUserId(userId);
		if (user == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该用户不存在！");
		} else if (account == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该用户账户不存在！");
		} else {
			// 不校验，直接扣成负的，反正也要不到钱
			userService.updateAccountByUserId(userId, money, isAdd);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/varietyMgnt")
	public ModelAndView varietyMgnt() {
		ModelAndView mav = new ModelAndView("mgnt/varietyMgnt");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/deleteVariety")
	@ResponseBody
	public String deleteVariety(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Variety variety = petService.findVarietyById(id);
		if (variety == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该品种不存在！");
		} else if (variety.getId() == Variety.VARIETY_DEFAULT_CAT
				|| variety.getId() == Variety.VARIETY_DEFAULT_DOG) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "默认品种不可删除！");
		} else {
			PetCondition conditions = new PetCondition();
			String[] varietys = { variety.getVarietyName() };
			conditions.setVarietys(varietys);
			if (petService.countPetByConditions(conditions) > 0) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "有在售的该品种宠物，不可删除！");
			} else {
				petService.deleteVariety(id);
				resultMap.put("msg", "success");
			}
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/updateVarietyDes")
	@ResponseBody
	public String updateVarietyDes(Integer id, String description) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Variety variety = petService.findVarietyById(id);
		if (variety == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该品种不存在！");
		} else {
			variety.setDescription(description);
			petService.updateVariety(variety);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/newVariety")
	public ModelAndView newVariety() {
		ModelAndView mav = new ModelAndView("mgnt/newVariety");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/addVariety")
	@ResponseBody
	public String addVariety(Variety variety) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (!petService.checkVariety(variety.getVarietyName())) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "存在同名品种！");
		} else {
			petService.addVariety(variety);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/petMgnt")
	public ModelAndView petMgnt() {
		ModelAndView mav = new ModelAndView("mgnt/petMgnt");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/findAllPet")
	@ResponseBody
	public String findAllPet(Pagination pagination) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rows", petService.findAllPet(pagination));
		resultMap.put("total", petService.countAllPet());
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/deletePet")
	@ResponseBody
	public String deletePet(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Pet pet = petService.findById(id);
		if (pet == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该宠物不存在！");
		} else {
			petService.delete(pet.getId());
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/orderMgnt")
	public ModelAndView orderMgnt() {
		ModelAndView mav = new ModelAndView("mgnt/orderMgnt");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/findAllOrder")
	@ResponseBody
	public String findAllOrder(Pagination pagination) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rows", orderService.findAll(pagination));
		resultMap.put("total", petService.countAllPet());
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/findOrderByorderNo")
	@ResponseBody
	public String findOrderByorderNo(String orderNo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 理论上只有一条，就不传分页信息了
		resultMap.put("rows", orderService.findByOrderNo(orderNo));
		resultMap.put("total", orderService.findByOrderNo(orderNo).size());
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/receiveOrder")
	@ResponseBody
	public String receiveOrder(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Order order = orderService.findById(id);
		if (order == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该订单不存在！");
		} else if (order.getState() != Order.ORDER_STATE_TORECEIVE) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该订单不是待收货状态！");
		} else {
			orderService.receive(id);
			userService.updateAccountByUserId(order.getSellerId(),
					order.getPrice(), true);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/cancelOrder")
	@ResponseBody
	public String cancelOrder(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Order order = orderService.findById(id);
		if (order == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该订单不存在！");
		} else if (order.getState() == Order.ORDER_STATE_DONE) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该订单已完成，无法取消！");
		} else {
			if (order.getState() == Order.ORDER_STATE_TOSEND
					|| order.getState() == Order.ORDER_STATE_TORECEIVE) {
				userService.updateAccountByUserId(order.getBuyerId(),
						order.getPrice(), true);
			}
			Pet pet = petService.findById(order.getPetId());
			if (pet != null) { // 可能已被管理员删除
				pet.setBuyerId(0);
				petService.update(pet);
			}
			orderService.delete(id);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}
}
